<!-- 卡券详情 -->
<template>
    <div class="van-safe-area-bottom">
        <van-nav-bar title="卡券详情" left-arrow :border="false" @click-left="onClickLeft"/>
        <div class="content">
            <div class="head">
                <img class="detailImg" :src="item.detailPicture" alt="">
                <div class="headCont">
                    <div class="productName">
                        <span>{{item.productName}}</span>
                        <span class="productNameTag">限时优惠</span>
                    </div>
                    <div style="font-size: 12px;color: #999999">{{item.description}}</div>
                    <div class="productPrice">￥{{item.price}}<span class="facePrice">原价￥{{item.facePrice}}</span></div>
                </div>
            </div>
            <div class="account">
                <div class="accountCont">
                    <van-field input-align="center" v-model="account" type="tel" placeholder="请输入充值号码" />
                </div>
                <div style="margin-top: 10px;font-size: 14px">
                    <span style="color: red">注：</span>请根据输入框提示，输入正确充值账号，虚拟商品一旦输错无法退款！
                </div>
            </div>
            <!-- 充值渠道 -->
            <div class="channel">
                <div @click="changeChannel(item)" class="channelItem flex alignCenter justifyBetween" v-for="item in channelList" :key="item.id">
                    <div class="flex alignCenter"><img :src="item.icon" alt="">{{item.name}}</div>
                    <img v-if="item.id == activeChannel" class="activeIcon" src="@/assets/lifePayCost/activeIcon.png" alt="">
                    <img v-else src="@/assets/lifePayCost/unActiveIcon.png" alt="">
                </div>
            </div>
        </div>

        <div class="bottom">
            <div class="bottomLeft allFlex">
                <div class="itemEvn" @click="goKefu">
                    <img src="@/assets/lifePayCost/cardCoupon/kefuIcon.png" alt="">
                    <div>客服</div>
                </div>
                <div class="itemEvn" @click="goBill">
                    <img src="@/assets/lifePayCost/cardCoupon/dingdanIcon.png" alt="">
                    <div>订单</div>
                </div>
            </div>
            <div class="submit" @click="submit">支付{{item.price}}元</div>
        </div>
    </div>
</template>

<script>
import { ref, reactive, getCurrentInstance } from 'vue'
import { Field , CellGroup , NavBar } from 'vant';
import storage from 'store';
import { getUserAgent } from '@/utils';
import { userAgent , BRANDID } from '@/utils/types';
import { dataEncryption , delNoneParameter } from '@/utils';
import qs from 'qs'
export default {
    components: {
        [Field.name]: Field,
        [CellGroup.name]: CellGroup,
        [NavBar.name]: NavBar,
    },
    setup() {
        const { proxy } = getCurrentInstance();
        const appId = storage.get('appId')
        const brandId = storage.get(BRANDID)
        // 返回上一页
        const onClickLeft = () => history.back();
        const getConfig = () =>{
            let url = window.location.href.split('#')[0]
            // var url = 'https://szk.lexiangaysh.cn/'
            proxy.$http.externalApi.queryWxConfig(url,storage.get(BRANDID))
            .then(res=>{
                if(res.success){
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: appId, // 必填，公众号的唯一标识
                        timestamp: Number(res.data.timestamp), // 必填，生成签名的时间戳
                        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                        signature: res.data.signature,// 必填，签名
                        jsApiList: ['updateAppMessageShareData','chooseWXPay'], // 必填，需要使用的JS接口列表
                    })
                }
            })
        }
        // 用户终端
        const userAgents = getUserAgent()
        if(userAgents == userAgent.WECHAT){
            getConfig();
        }

        const item = JSON.parse(proxy.$route.params.item)
        console.log(item,'item');

        // 跳转客服
        const goKefu = () => {
            proxy.$router.push({name: 'customerService'})
        }
        // 跳转订单
        const goBill = () => proxy.$router.push({name: 'lifePayCostBillBefore',params: {'orderType': 5}});

        // 账号
        const account = ref('');
        // 商户号
        const merchantNo = storage.get('merchantNo');

        // 选择充值渠道
        const activeChannel = ref(2);
        const channelList = [
            { 'id': 1, 'name': '支付宝', 'icon': require('../../../assets/lifePayCost/zhfbIcon.png')},
            { 'id': 2, 'name': '微信', 'icon': require('../../../assets/lifePayCost/wxIcon.png')},
        ];
        const changeChannel = (item) =>{
            activeChannel.value = item.id;
        }

        // 支付
        const submit = () => {
            if(account.value == ''){
                proxy.$toast({message: '请输入充值账号！',position: 'bottom'})
                return;
            }
            if(userAgents !== userAgent.WECHAT && activeChannel.value == 2){
                proxy.$toast({message: '微信支付必须要在微信浏览器内支付，请更换其他支付方式',position: 'bottom'})
                return;
            }
            proxy.$dialog.confirm({
                title: '温馨提示',
                message: `请确认充值账号：${account.value} ，充值产品：${item.productName} ？`,
            }).then(()=>{confirmProduct(item);})
        }
        const confirmProduct = (item) =>{
            proxy.$http.externalApi.newCardCouponPlaceOrder({merchantNo: merchantNo,account: account.value,productId: item.productId})
            .then(async res=>{
                if(res.success){
                    if(userAgents == userAgent.WECHAT){
                        if(activeChannel.value == 2){
                            var openId = await getOpenId();
                            pay(res.data,{openId: openId})
                        }else{
                            const params = {
                                'merchantNo': merchantNo,
                                'orderCode': res.data,
                                'payType': activeChannel.value,
                            }
                            const objPar = delNoneParameter(Object.assign(qs.parse(qs.stringify(params)),dataEncryption(qs.parse(qs.stringify(params)))))
                            let paramsArr = new Array()
                            // console.log(dataObj)
                            Object.keys(objPar).sort().map(function(key){
                                // 判断key值的类型，文件的过滤掉
                                if(typeof(objPar[key]) != 'object'  && objPar[key] !== "" && objPar[key] != undefined){
                                    paramsArr.push(
                                    key + '=' + objPar[key]
                                    )
                                }
                            })
                            let paramsStr = paramsArr.join('&')
                            var url = `https://${window.location.host}${process.env.VUE_APP_API_BASE_URL}/open/api/promotion/recharge/pay?${paramsStr}`;
                            proxy.$router.push({name: 'gathering', params: {'title': '支付宝支付','money': item.price, 'url': url}})
                        }
                    }else{
                        pay(res.data,{openid: undefined})
                    }
                }else{
                    proxy.$toast({position: 'bottom',message:res.errMessage})
                }
            })
        }
        // 支付
        const pay = (orderCode,{openId = ''}) =>{
            proxy.$http.externalApi.promotionRechargePay({merchantNo: merchantNo,orderCode: orderCode,payType: activeChannel.value,openId: openId})
            .then(res=>{
                if(userAgents != userAgent.WECHAT){
                    var div = document.createElement('div')
                    div.innerHTML = res
                    document.body.appendChild(div)
                    document.forms[0].submit()
                }else{
                    if(res.success){
                        // 微信下需要掉起微信支付，微信外处理支付宝返回数据
                        if(userAgents == userAgent.WECHAT){
                            var resData = JSON.parse(res.data)
                            console.log(resData,'resData')
                            // alert(resData)
                            wx.chooseWXPay({
                                timestamp: resData.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                                nonceStr: resData.nonceStr, // 支付签名随机串，不长于 32 位
                                package: resData.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                                signType: resData.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                                paySign: resData.paySign, // 支付签名
                                appId: resData.appId,
                                success: function (res) {
                                    // 支付成功后的回调函数
                                    proxy.$toast({message: '支付成功',position: 'bottom'})
                                },
                            });
                        }
                    }else{
                        proxy.$toast({position: 'bottom',message:res.errMessage})
                    }
                }
            })
        }
        // 微信支付需要获取用户的OpenId
        const getOpenId = () =>{
            return new Promise((resolve,reject) =>{
                proxy.$http.externalApi.queryWxOpenId({code: storage.get('code'),brandId: storage.get(BRANDID)})
                .then(res=>{
                    if(res.success){
                        resolve(res.data.openid)
                    }else{
                        proxy.$toast({position: 'bottom',message:res.errMessage})
                    }
                })
            })
        }

        return { 
            onClickLeft,
            item,
            goKefu,
            goBill,
            account,
            channelList,
            activeChannel,
            changeChannel,
            submit,
        }
    }
}

</script>
<style scoped>
.content{
    padding: 10px 15px 85px;
}
/* 商品信息 */
.head{
    background: #FFFFFF;
    border-radius: 8px;
    overflow: hidden;
}
.detailImg{
    width: 100%;
    height: 275px;
}
.headCont{
    padding: 15px 10px;
}
.productName{
    font-size: 16px;
    font-weight: 500;
    color: #333;
}
.productNameTag{
    display: inline-block;
    width: 45px;
    height: 17px;
    border-radius: 3px;
    background: #EECD8C;
    line-height: 17px;
    text-align: center;
    font-size: 10px;
    color: #AC753C;
    margin-left: 8px;
}
.productPrice{
    font-size: 21px;
    color: #FF1839;
    font-weight: 500
}
.productPrice .facePrice{
    font-size: 12px;
    color: #999999;
    margin-left: 5px;
    text-decoration: line-through;
}

/* 充值账号 */
.account{
    background: #FFFFFF;
    border-radius: 5px;
    padding: 10px;
    margin: 5px 0;
}
.accountCont /deep/ .van-cell{
    height: 47px;
    border-radius: 5px;
    background: #F2F4F7;
    font-size: 16px;
    line-height: 47px;
    padding: 0;
}
.accountCont .input::placeholder{
    color: #999999;
}

/* 底部功能按钮 */
.bottom{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 50px;
    padding-bottom: 30px;
    background: #FFFFFF;
    display: flex;
    align-items: center;
}
.submit{
    background: #FF1839;
    height: 36px;
    line-height: 36px;
    text-align: center;
    border-radius: 20px;
    color: #FFFFFF;
    font-size: 14px;
    width: 136px;
    margin-right: 14px;
}
.bottomLeft{
    display: flex;
    justify-content: space-around;
}
.itemEvn{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #666666;
}
.itemEvn img{
    width: 22.5px;
    height: 22.5px;
}

/* 充值渠道 */
.channel,.desc{
    margin: 5px 0px;
    border-radius: 8px;
    background: #FFFFFF;
    padding: 5px 10px;
}
.channelItem{
    height: 45px;
    font-size: 15px;
    color: #333333;
}
.channelItem img{
    width: 18px;
    height: 18px;
    margin-right: 10px;
    display: inline-block;
}
</style>